package cn.mashiro.common.restful;

import cn.mashiro.common.enums.ResultCode;
import cn.mashiro.common.execption.ServiceException;

public class Result<T> {
    private final int code;

    private final String message;

    private final T data;

    public Result() {
        this.data = null;
        this.code = ResultCode.SUCCESS.getCode();
        this.message = ResultCode.SUCCESS.getMessage();
    }

    public Result(T data) {
        this.data = data;
        this.code = ResultCode.SUCCESS.getCode();
        this.message = ResultCode.SUCCESS.getMessage();
    }

    public Result(Exception exception) {
        this.data = null;
        this.code = ResultCode.ERROR.getCode();
        this.message = ResultCode.ERROR.getMessage();
    }

    public Result(ServiceException exception) {
        this.data = null;
        this.code = exception.getCode();
        this.message = exception.getMessage();
    }

    public static <T> Result<T> success() {
        return new Result<>();
    }

    public static <T> Result<T> success(T data) {
        return new Result<>(data);
    }

    public static <T> Result<T> error(Exception exception) {
        if (exception instanceof ServiceException) {
            return new Result<>((ServiceException) exception);
        }
        return new Result<>(exception);
    }

    public static <T> Result<T> error(ServiceException exception) {
        return new Result<>(exception);
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }
}
